package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.R;
import com.hmall.search.service.SearchService;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ItemClient itemClient;
    /**
     * 自动补全
     * @param key 补全关键字
     * @return
     * @throws IOException
     */
    @Override
    public List<String> getSuggestion(String key) throws IOException {
        SearchRequest request = new SearchRequest("item");
        //去除搜索的_source   无用的信息
        request.source().fetchSource(new String[0],null);

        //设置查询条件
        request.source().suggest(new SuggestBuilder()
                .addSuggestion("title_suggest", SuggestBuilders.completionSuggestion("suggestion")
                .size(10)
                .skipDuplicates(true)
                .prefix(key)
                ));
        //查询
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //解析
        CompletionSuggestion suggest = search.getSuggest().getSuggestion("title_suggest");

        List<CompletionSuggestion.Entry.Option> options = suggest.getOptions();

        ArrayList<String> list = new ArrayList<>();

        for (CompletionSuggestion.Entry.Option option : options) {
            String string = option.getText().string();
            list.add(string);
        }

        return list;
    }

    @Override
    public Map<String, List<String>> getFilters(R r) throws IOException {

        SearchRequest request = new SearchRequest("item");
        //不要数据的具体内容
        request.source().size(0);

        //条件查询过滤
        requestQuery(r,request);

        request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(9));
        request.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(9));

        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        Aggregations aggregations = search.getAggregations();
        Terms brandAgg = aggregations.get("brandAgg");
        HashMap<String, List<String>> map = new HashMap<>();
        ArrayList<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            String keyAsString = bucket.getKeyAsString();
            brandList.add(keyAsString);
        }
        map.put("brand", brandList);

        ArrayList<String> categoryList = new ArrayList<>();
        Terms categoryAgg = aggregations.get("categoryAgg");

        for (Terms.Bucket bucket : categoryAgg.getBuckets()) {
            String keyAsString = bucket.getKeyAsString();
            categoryList.add(keyAsString);
        }
        map.put("category",categoryList );
        return map;
    }



    @Override
    public PageDTO<ItemDoc> page(R r) throws IOException {
        SearchRequest request = new SearchRequest("item");
        requestQuery(r, request);

        request.source().from((r.getPage()-1)*r.getSize()).size(r.getSize());

        String sortBy = r.getSortBy();
        if ("sold".equals(sortBy)){
            request.source().sort(sortBy, SortOrder.DESC);
        }else if ("price".equals(sortBy)){
            request.source().sort(sortBy, SortOrder.ASC);
        }

        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));


        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        SearchHits searchHits = search.getHits();

        long value = searchHits.getTotalHits().value;

        SearchHit[] hits = searchHits.getHits();
        ArrayList<ItemDoc> itemDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);

            Map<String, HighlightField> map = hit.getHighlightFields();
            if (map !=null &&map.size()>0){
                HighlightField name = map.get("name");
                String s = name.getFragments()[0].toString();
                itemDoc.setName(s);

            }
            itemDocs.add(itemDoc);
        }

        return new PageDTO<>(value,itemDocs);
    }


    @Override
    public void upById(Long id) {
        try {
            Item byId = itemClient.getById(id);
            IndexRequest item = new IndexRequest("item").id(id.toString());
            item.source(JSON.toJSON(new ItemDoc(byId)), XContentType.JSON);
            restHighLevelClient.index(item, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void downById(Long id) {
        try {
            DeleteRequest item = new DeleteRequest("item",id.toString());
            restHighLevelClient.delete(item, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加查询条件
     * @param r 储存条件的对象
     * @param request
     */
    private void requestQuery(R r, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字查询
        String key = r.getKey();
        if (key!=null && key.length()>0){
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        //分类查询
        String brand = r.getBrand();
        if (brand !=null && brand.length()>0){
            boolQuery.filter(QueryBuilders.termQuery("brand",brand ));
        }
        //品牌查询
        String category = r.getCategory();
        if (category !=null && category.length()>0){
            boolQuery.filter(QueryBuilders.termQuery("category",category ));
        }
        //价格查询
        Long minPrice = r.getMinPrice();
        Long maxPrice = r.getMaxPrice();
        if (minPrice==null){
            minPrice=0L;
        }
        if (maxPrice==null){
            maxPrice=Long.MAX_VALUE;
        }else {
            maxPrice=maxPrice*100;
        }
        boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice*100).lte(maxPrice));
        FunctionScoreQueryBuilder isAD = QueryBuilders.functionScoreQuery(
                boolQuery, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(1000)
                        )
                }
        );

        request.source().query(isAD);
    }
}
